package com.warmheart.controller.common;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.warmheart.base.annotation.Auth;
import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.config.WhFileUploadService;
import com.warmheart.base.controller.BaseController;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;

/**
 * 
 * @ClassName: CommonController
 * @Description: 通用控制器
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
@RestController
@RequestMapping("/common")
public class CommonController extends BaseController {

    // 注入上传service
    @Autowired(required = false)
    private WhFileUploadService whFileUploadService;

    /**
     * 
     * @Title: upload
     * @Description: 上传文件
     * @author ZhangJianyang
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Duplicate(validate = true)
    @RequestMapping("/upload")
    public CommonResult<Map<String, Object>> upload(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件
        MultipartFile multipartFile = multipartRequest.getFile("file");
        Map<String, String> fileMap = whFileUploadService.uploadCommonSelf(multipartFile);
        if (fileMap == null || fileMap.isEmpty()) {
            return CommonResult.failed(ResultCode.ERROR_SERVER, "上传文件失败");
        }
        resultMap.put("netPath", fileMap.get("netPath"));
        resultMap.put("netUrl", fileMap.get("netUrl"));
        return CommonResult.success("上传文件成功", resultMap);
    }
}
